﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using LuaInterface;

public class LuaComponent : MonoBehaviour {
	// lua file
	public string luaFile;

	// 
	private LuaState luaState; 

	public LuaTable luaTable {
		get;
		private set;
	}
		
	private LuaFunction funcStart = null;

	private LuaTable luaInstance = null;

	// function
	private void Init() {
		luaState = LuaClient.GetMainState();

		if (luaFile == string.Empty) {
			Debug.LogWarning ("LuaFile is empty! GameObject name is " + gameObject.name);
			return;
		}

		object[] result = luaState.DoFile (luaFile);
		if (result == null || result.Length == 0) {
			Debug.LogWarning ("LuaState dofile LuaFile error! No result return! luafile is " + luaFile);
			return;
		}
		luaTable = (LuaTable)result [0];
		funcStart = luaTable.GetLuaFunction ("Start");
		if (funcStart == null) {
			Debug.LogWarning ("LuaTable get LuaFunction error! No Start function! lua file is " + luaFile);
		}
	}

	// Use this for initialization
	void Start () {
		
		Init ();

		if (funcStart != null) {
			object[] ret = funcStart.Call (gameObject);
			if (ret != null && ret.Length > 0) {
				luaInstance = ret [0] as LuaTable;
				if (luaInstance == null) {
					Debug.LogWarning ("LuaTable Start Function, the first return value is not a lua table!" + luaFile);
				}
			} else {
				Debug.LogWarning ("LuaTable Start Function doesn't return value!" + luaFile);
			}
			funcStart.Dispose ();
			funcStart = null;
		}
	}
	
	// Update is called once per frame
	void Update () {


	}

	void OnDestroy() {

		LuaFunction funcDestroy = null;
		if (luaTable != null) {
			funcDestroy = luaTable.GetLuaFunction ("Destroy");
			if (funcDestroy != null) {
				funcDestroy.Call (gameObject, luaInstance);
				funcDestroy.Dispose ();
				funcDestroy = null;
			} else {
				Debug.LogWarning ("LuaTable get LuaFunction error! No Destroy function! lua file is " + luaFile);
			}
		}

		if (luaTable != null) {
			luaTable.Dispose ();
			luaTable = null;
		}

		// 后续可以添加检查gameObject的引用计数情况来检查内存泄漏

		luaState = null;
	}
}
